#!/bin/bash

set -e

# 函数：验证包文件是否存在
validate_pkg_file() {
    if [[ ! -f "$1" ]]; then
        echo "包文件不存在：$1 / The package file does not exist: $1"
        exit 1
    fi
}

# 检查是否有任何参数传入
if [ "$1"  = "" ];then
        echo "用法：$0 [--orig-pkg-file=FILE_PATH --version=VERSION [--new-pkg-name=NAME]] / Usage: $0 [--orig-pkg-file=FILE_PATH --version=VERSION [--new-pkg-name=NAME]]"
        exit 1
fi

# 初始化参数变量
NEW_PKG_NAME=""
ORIG_PKG_FILE=""
VERSION=""

# 解析命令行参数
for i in "$@"; do
    case $i in
        --new-pkg-name=*)
        NEW_PKG_NAME="${i#*=}"
        shift
        ;;
        --orig-pkg-file=*)
        ORIG_PKG_FILE="${i#*=}"
        validate_pkg_file $ORIG_PKG_FILE || exit 1
        shift
        ;;
        --version=*)
        VERSION="${i#*=}"
        shift
        ;;
        *)
        # 如果发现无法识别的选项，显示脚本用法
        echo "用法：$0 [--orig-pkg-file=FILE_PATH --version=VERSION [--new-pkg-name=NAME]] / Usage: $0 [--orig-pkg-file=FILE_PATH --version=VERSION [--new-pkg-name=NAME]]"
        exit 1
        ;;
    esac
done

# 检查原始包文件路径是否已设置，这是必需的
if [ -z "$ORIG_PKG_FILE" ]; then
    echo "错误：必须提供 --orig-pkg-file 选项。/ Error: --orig-pkg-file option is required."
    exit 1
fi

# 检查系统是否安装了 wget
if [ "$(which wget)" = "" ]; then
    echo "错误：首先你需要安装 wget。/ Nope, you need wget first."
    exit
fi

# 如果未提供新包名，则使用 dpkg -f 读取原始包文件的包名
if [ -z "$NEW_PKG_NAME" ]; then
    NEW_PKG_NAME=$(dpkg-deb -f "$ORIG_PKG_FILE" Package)
    if [ -z "$NEW_PKG_NAME" ]; then
        echo "无法从原始包文件中读取包名，请手动提供 --new-pkg-name 参数。/ Unable to read package name from original package file, please provide --new-pkg-name option manually."
        exit 1
    fi
fi





# Step 1: Get the version number and other details of the original package

ORIG_PKG_FILE_NAME=$(basename "$ORIG_PKG_FILE")
# Extract package information from the original package file
ORIG_PKG_NAME=$(dpkg-deb -f "$ORIG_PKG_FILE" Package)
if [ -z "$VERSION" ]; then
    VERSION=$(dpkg-deb -f "$ORIG_PKG_FILE" Version)
fi

MAINTAINER=$(dpkg-deb -f "$ORIG_PKG_FILE" Maintainer )
DESCRIPTION=$(dpkg-deb -f "$ORIG_PKG_FILE" Description)
HOMEPAGE="https://gitee.com/spark-building-service/ace-host-package-creator"

# Check if the version number was retrieved successfully
if [ -z "$VERSION" ]; then
    echo "Error: Unable to retrieve the version number for the package $ORIG_PKG_NAME."
    exit 1
fi

# Step 2: Create the directory structure for the new package
PKG_DIR="$(mktemp -d)"
DEBIAN_DIR="${PKG_DIR}/DEBIAN"
mkdir -p "$DEBIAN_DIR"
mkdir -p "${PKG_DIR}/opt/${ORIG_PKG_NAME}_install_file/"
cp -v $ORIG_PKG_FILE ${PKG_DIR}/opt/${ORIG_PKG_NAME}_install_file/
# Step 3: Create and modify the control file with the details from the original package
cat > "${DEBIAN_DIR}/control" << EOF
Package: $NEW_PKG_NAME
Version: $VERSION
Maintainer: $MAINTAINER
Priority: optional
Section: utils
Installed-Size: 10
Depends: amber-ce-loongnix,bash,wget,sudo,libnotify-bin
Description: $DESCRIPTION
Architecture: loong64
Homepage: $HOMEPAGE
EOF


# Step 4: Create and write the postinst and postrm scripts
echo "#!/bin/bash " > "${DEBIAN_DIR}/postinst"
echo "REAL_PACKAGE=$ORIG_PKG_NAME" >> "${DEBIAN_DIR}/postinst"
echo "ORIG_PKG_FILE_NAME=$ORIG_PKG_FILE_NAME" >> "${DEBIAN_DIR}/postinst"
cat >> "${DEBIAN_DIR}/postinst" << 'EOF'
function notify-send(){
 #Detect the user using such display
    local user=$(who | awk '{print $1}' | head -n 1)

    #Detect the id of the user
    local uid=$(id -u $user)
sudo -u $user DBUS_SESSION_BUS_ADDRESS=unix:path=/run/user/$uid/bus notify-send "$@"
}

function zenity(){
 #Detect the user using such display
    local user=$(who | awk '{print $1}' | head -n 1)

    #Detect the id of the user
    local uid=$(id -u $user)
sudo -u $user DBUS_SESSION_BUS_ADDRESS=unix:path=/run/user/$uid/bus zenity "$@"
}

###检查aptss在不在
if [ -z `which loongnix-run` ];then
echo "Oh no, ssinstall have not installed loongnix-run dependency yet! Exit"
exit 1
fi
IS_ACE_ENV=1 loongnix-run echo "Welcome to BCM! Trying to install package"
if [ -z "`loongnix-run which aptss`" ];then
wget https://amber-ce-resource.spark-app.store/store/depends/spark-store-console-in-container_latest_all.deb -O /tmp/ssconsole.deb
IS_ACE_ENV=1 loongnix-run apt update
IS_ACE_ENV=1 loongnix-run apt install /tmp/ssconsole.deb -y
rm /tmp/ssconsole.deb -f
fi

notify-send "Installing $REAL_PACKAGE ACE, may cost some time please ensure your network is fine" 
notify-send "正在ACE兼容环境中安装$REAL_PACKAGE，可能会花费一些时间，请保持网络畅通" 
IS_ACE_ENV=1 loongnix-run  aptss install aptss --only-upgrade -y
IS_ACE_ENV=1 loongnix-run /usr/local/bin/ssaudit /host/opt/${REAL_PACKAGE}_install_file/${ORIG_PKG_FILE_NAME}

IS_ACE_ENV=1 loongnix-run aptss clean

EOF

echo "#!/bin/bash" > "${DEBIAN_DIR}/postrm"
echo "REAL_PACKAGE=$ORIG_PKG_NAME" >> "${DEBIAN_DIR}/postrm"
cat >> "${DEBIAN_DIR}/postrm" << 'EOF'


loongnix-run echo "Welcome to ACE! Trying to remove package"

if [ "$1" = "remove" ] || [ "$1" = "purge" ];then

loongnix-run apt autopurge $REAL_PACKAGE -y
loongnix-run apt clean
else
echo "非卸载，跳过卸载"
fi
true
EOF


chmod +x "${DEBIAN_DIR}/postinst"
chmod +x "${DEBIAN_DIR}/postrm"

# Step 5: Build the new .deb package
dpkg-deb -Z gzip --build $PKG_DIR "$(pwd)"
rm -rf $PKG_DIR
